import os
import tkinter as tk
from tkinter import ttk, scrolledtext, Toplevel, PhotoImage, CENTER, Label, BOTH
import windnd
from PIL import Image
from datetime import datetime
from zsm import *


class LongImageSplitter:
    def __init__(self, root):
        self.root = root
        self.root.title("长图分割合并PDF工具       By:风二西  2025.03.02")
        self.root.geometry("500x150")

        # 消息输出框
        self.msg_text = scrolledtext.ScrolledText(root, height=6,
                                                  wrap=tk.WORD,
                                                  state='disabled',
                                                  bg="Ivory")
        self.msg_text.pack(fill=tk.BOTH, expand=True, padx=10, pady=5)

        # 底部信息栏
        bottom_frame = ttk.Frame(root)
        bottom_frame.pack(side=tk.BOTTOM, fill=tk.X, padx=10, pady=5)
        ttk.Button(bottom_frame, text="赞赏作者",
                   command=self.donate_author).pack(side=tk.LEFT)
        ttk.Label(bottom_frame,
                  text="拖入长图自动分割为A4的纵向PDF").pack(side=tk.RIGHT)

        windnd.hook_dropfiles(self.root, func=self.handle_drop)

    def handle_drop(self, files):
        try:
            file_path = files[0].decode('gbk')
            if not file_path.lower().endswith(('.png', '.jpg', '.jpeg')):
                raise ValueError("仅支持PNG/JPG格式图片")

            self.process_long_image(file_path)

        except Exception as e:
            self.show_message(f"错误：{str(e)}", 'error')

    def process_long_image(self, img_path):
        try:
            with Image.open(img_path) as img:
                # 调整图片宽度至A4尺寸（210mm @300dpi = 2480px）
                a4_width = 2480
                a4_height = 3508  # 297mm = 3508px

                # 计算缩放后的高度
                scaling_factor = a4_width / img.width
                scaled_height = int(img.height * scaling_factor)

                # 高质量缩放
                resized_img = img.resize((a4_width, scaled_height), Image.LANCZOS)

                # 生成输出路径
                base_name = os.path.splitext(img_path)[0]
                pdf_path = f"{base_name}_分割版.pdf"

                # 执行分割
                self.split_long_image(resized_img, a4_width, a4_height, pdf_path)

                self.show_message(f"✅ 分割完成！保存到：{pdf_path}", 'success')
                # os.startfile(os.path.dirname(pdf_path))  # 打开输出目录

        except Exception as e:
            self.show_message(f"❌ 分割失败：{str(e)}", 'error')

    def split_long_image(self, img, page_w, page_h, pdf_path):
        """执行纵向分割（固定A4尺寸）"""
        pdf_pages = []
        img_width, img_height = img.size
        y_pos = 0  # 起始位置

        try:
            while y_pos < img_height:
                # 计算当前页高度
                current_h = min(page_h, img_height - y_pos)

                # 裁剪区域（左，上，右，下）
                crop_area = (0, y_pos, img_width, y_pos + current_h)
                page = img.crop(crop_area)

                # 创建A4页面（自动处理高度不足）
                a4_page = Image.new('RGB', (page_w, page_h), (255, 255, 255))
                a4_page.paste(page, (0, 0))  # 内容顶部对齐

                pdf_pages.append(a4_page)
                y_pos += current_h

            # 保存PDF
            if pdf_pages:
                pdf_pages[0].save(pdf_path, "PDF",
                                  resolution=300.0,
                                  save_all=True,
                                  append_images=pdf_pages[1:])
            else:
                raise ValueError("未生成有效页面")

        finally:
            for page in pdf_pages:
                page.close()

    def show_message(self, message, msg_type='info'):
        timestamp = datetime.now().strftime("%H:%M:%S")
        self.msg_text.configure(state='normal')
        self.msg_text.insert(tk.END, f"[{timestamp}] ", 'timestamp')
        self.msg_text.insert(tk.END, message + '\n', msg_type)
        self.msg_text.see(tk.END)
        self.msg_text.configure(state='disabled')
        self.root.update_idletasks()

    def donate_author(self):
        self.zsm_windows = Toplevel(self.root)
        self.zsm_windows.wm_attributes("-topmost", 1)
        self.zsm_windows.title('赞赏作者')
        self.photo1 = PhotoImage(data=zsm123)
        self.zsm1 = Label(self.zsm_windows, image=self.photo1, compound=CENTER)
        self.zsm1.pack(fill=BOTH, expand=True)


if __name__ == "__main__":
    root = tk.Tk()
    app = LongImageSplitter(root)
    app.msg_text.tag_config('timestamp', foreground='gray')
    app.msg_text.tag_config('success', foreground='darkgreen')
    app.msg_text.tag_config('error', foreground='red')
    root.mainloop()